import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { Agent, SearchFilters } from "../types";

export const useAgentsStore = defineStore("agents", () => {
    // State
    const agents = ref<Agent[]>([]);
    const featuredAgents = ref<Agent[]>([]);
    const isLoading = ref(false);
    const searchFilters = ref<SearchFilters>({
        query: "",
        categories: [],
        pricing: [],
        rating: { min: 0, max: 5 },
        features: [],
        sortBy: "relevance",
        sortOrder: "desc",
    });

    // Getters
    const filteredAgents = computed(() => {
        let filtered = [...agents.value];

        // Filter by search query
        if (searchFilters.value.query) {
            const query = searchFilters.value.query.toLowerCase();
            filtered = filtered.filter(
                (agent) =>
                    agent.name.toLowerCase().includes(query) ||
                    agent.description.toLowerCase().includes(query)
            );
        }

        // Filter by categories
        if (searchFilters.value.categories.length > 0) {
            filtered = filtered.filter((agent) =>
                searchFilters.value.categories.includes(agent.category)
            );
        }

        // Filter by pricing
        if (searchFilters.value.pricing.length > 0) {
            filtered = filtered.filter((agent) =>
                searchFilters.value.pricing.includes(agent.pricing.model)
            );
        }

        // Filter by rating
        filtered = filtered.filter(
            (agent) =>
                agent.metadata.rating >= searchFilters.value.rating.min &&
                agent.metadata.rating <= searchFilters.value.rating.max
        );

        // Sort
        filtered.sort((a, b) => {
            let comparison = 0;
            switch (searchFilters.value.sortBy) {
                case "price":
                    const priceA = a.pricing.price || 0;
                    const priceB = b.pricing.price || 0;
                    comparison = priceA - priceB;
                    break;
                case "rating":
                    comparison = a.metadata.rating - b.metadata.rating;
                    break;
                case "newest":
                    comparison =
                        new Date(a.metadata.createdAt).getTime() -
                        new Date(b.metadata.createdAt).getTime();
                    break;
                default: // relevance
                    comparison = b.metadata.usageCount - a.metadata.usageCount;
            }
            return searchFilters.value.sortOrder === "asc"
                ? comparison
                : -comparison;
        });

        return filtered;
    });

    // Actions
    const fetchAgents = async () => {
        isLoading.value = true;
        try {
            // TODO: Implement actual API call
            // const response = await agentsApi.getAgents()

            // Mock data for now
            const mockAgents: Agent[] = [
                {
                    id: "1",
                    name: "TikTok Data Analyst",
                    description:
                        "Professional TikTok video data analysis and trend prediction with comprehensive social media insights and audience behavior analysis.",
                    category: "analysis",
                    pricing: { model: "free" },
                    capabilities: {
                        apiCalls: ["tiktok-api", "analytics-api"],
                        thirdPartyLibraries: ["pandas", "numpy"],
                        knowledgeBase: ["social-media", "data-analysis"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-01-01"),
                        updatedAt: new Date(),
                        creatorId: "analytics-pro",
                        usageCount: 12500,
                        rating: 4.8,
                        reviews: [],
                        githubStars: 0,
                        logo: "📊",
                    },
                    status: "active",
                },
                {
                    id: "2",
                    name: "AI Content Creator",
                    description:
                        "Intelligent generation of high-quality articles, blog posts, and marketing content with SEO optimization and brand voice consistency.",
                    category: "writing",
                    pricing: { model: "free" },
                    capabilities: {
                        apiCalls: ["openai-api", "seo-api"],
                        thirdPartyLibraries: ["content-tools"],
                        knowledgeBase: ["content-marketing", "seo"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-01-15"),
                        updatedAt: new Date(),
                        creatorId: "content-master",
                        usageCount: 18900,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "✍️",
                    },
                    status: "active",
                },
                {
                    id: "3",
                    name: "Senior Operations Director",
                    description:
                        "Expert in user growth strategies, product operations, and business process optimization with data-driven decision making.",
                    category: "automation",
                    pricing: { model: "paid", price: 150 },
                    capabilities: {
                        apiCalls: ["analytics-api", "crm-api"],
                        thirdPartyLibraries: ["business-tools"],
                        knowledgeBase: ["operations", "growth"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-02-01"),
                        updatedAt: new Date(),
                        creatorId: "ops-expert",
                        usageCount: 15600,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "🎯",
                    },
                    status: "active",
                },
                {
                    id: "4",
                    name: "Redis Senior Architect",
                    description:
                        "Specialized in Redis cluster deployment, performance optimization, and high-availability database architecture design.",
                    category: "coding",
                    pricing: { model: "paid", price: 200 },
                    capabilities: {
                        apiCalls: ["redis-api", "monitoring-api"],
                        thirdPartyLibraries: ["redis-tools"],
                        knowledgeBase: ["database", "performance"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-02-15"),
                        updatedAt: new Date(),
                        creatorId: "db-architect",
                        usageCount: 8900,
                        rating: 4.8,
                        reviews: [],
                        githubStars: 0,
                        logo: "🗄️",
                    },
                    status: "active",
                },
                {
                    id: "5",
                    name: "Kubernetes Cloud Architect",
                    description:
                        "Cloud native architecture specialist with expertise in Kubernetes cluster design, microservices deployment, and container orchestration.",
                    category: "coding",
                    pricing: { model: "paid", price: 180 },
                    capabilities: {
                        apiCalls: ["k8s-api", "cloud-api"],
                        thirdPartyLibraries: ["kubernetes-tools"],
                        knowledgeBase: ["cloud-native", "microservices"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-03-01"),
                        updatedAt: new Date(),
                        creatorId: "cloud-expert",
                        usageCount: 13400,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "☁️",
                    },
                    status: "active",
                },
                {
                    id: "6",
                    name: "Intelligent Customer Service",
                    description:
                        "Multilingual customer service specialist with intelligent Q&A capabilities, sentiment analysis, and automated ticket resolution.",
                    category: "digital-worker",
                    pricing: { model: "free" },
                    capabilities: {
                        apiCalls: ["nlp-api", "translation-api"],
                        thirdPartyLibraries: ["customer-tools"],
                        knowledgeBase: ["customer-service", "nlp"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-03-15"),
                        updatedAt: new Date(),
                        creatorId: "service-ai",
                        usageCount: 15600,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "🤝",
                    },
                    status: "active",
                },
                {
                    id: "7",
                    name: "AI Algorithm Engineer",
                    description:
                        "Machine learning engineer specializing in deep learning, NLP, and computer vision with model optimization and deployment expertise.",
                    category: "coding",
                    pricing: { model: "paid", price: 300 },
                    capabilities: {
                        apiCalls: ["ml-api", "gpu-api"],
                        thirdPartyLibraries: ["tensorflow", "pytorch"],
                        knowledgeBase: ["machine-learning", "deep-learning"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-04-01"),
                        updatedAt: new Date(),
                        creatorId: "ml-expert",
                        usageCount: 18700,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "🧠",
                    },
                    status: "active",
                },
                {
                    id: "8",
                    name: "AI Programming Assistant",
                    description:
                        "Advanced code generation and debugging assistant with support for multiple programming languages and real-time code analysis.",
                    category: "coding",
                    pricing: { model: "free" },
                    capabilities: {
                        apiCalls: ["code-api", "analysis-api"],
                        thirdPartyLibraries: ["code-tools"],
                        knowledgeBase: ["programming", "debugging"],
                        customConfiguration: {},
                    },
                    metadata: {
                        createdAt: new Date("2024-04-15"),
                        updatedAt: new Date(),
                        creatorId: "code-ai",
                        usageCount: 20300,
                        rating: 4.9,
                        reviews: [],
                        githubStars: 0,
                        logo: "💻",
                    },
                    status: "active",
                },
            ];

            agents.value = mockAgents;
            featuredAgents.value = mockAgents.slice(0, 6); // Top 6 for featured section
        } catch (error) {
            console.error("Error fetching agents:", error);
        } finally {
            isLoading.value = false;
        }
    };

    const updateSearchFilters = (filters: Partial<SearchFilters>) => {
        searchFilters.value = { ...searchFilters.value, ...filters };
    };

    const clearSearchFilters = () => {
        searchFilters.value = {
            query: "",
            categories: [],
            pricing: [],
            rating: { min: 0, max: 5 },
            features: [],
            sortBy: "relevance",
            sortOrder: "desc",
        };
    };

    return {
        // State
        agents,
        featuredAgents,
        isLoading,
        searchFilters,
        // Getters
        filteredAgents,
        // Actions
        fetchAgents,
        updateSearchFilters,
        clearSearchFilters,
    };
});
